package com.yonyou.pmclouds.pmpub;

import com.alibaba.dubbo.config.annotation.Service;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.consts.BillTypeConst;
import com.yonyou.pmclouds.basecom.entity.AdditionalPropertiesVOWrapper;
import com.yonyou.pmclouds.basecom.entity.Entity;
import com.yonyou.pmclouds.basecom.entity.SuperVO;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.util.BeanHelper;
import com.yonyou.pmclouds.basecom.util.DateUtils;
import com.yonyou.pmclouds.discuss.itf.DiscussInternalOperation;
import com.yonyou.pmclouds.pmpub.entity.PMListQueryResult;
import com.yonyou.pmclouds.pmpub.entity.QueryListParam;
import com.yonyou.pmclouds.pmpub.rmiitf.ICommonQueryService;
import com.yonyou.pmclouds.pmpub.rmiitf.IPageQuerySerivce;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service(version = ApplicationConsts.APPLICATION_VERSION, interfaceClass = ICommonQueryService.class)
public class CommonQuerySerivceImp implements ICommonQueryService {

    private  Map<String, IPageQuerySerivce> pageQueryServiceMap = new HashMap<String,IPageQuerySerivce>();

    public void putBuziQuerInfo(IPageQuerySerivce queryInfo) {
        if(BillTypeConst.SITEINSPECTION_BILLTYPE .equals(queryInfo.getBillType()) ){
            pageQueryServiceMap.put(BillTypeConst.PARALLEL_INSPECTION_BILLTYPE,queryInfo);
            pageQueryServiceMap.put(BillTypeConst.SIDE_INSPECTION_BILLTYPE ,queryInfo);
            pageQueryServiceMap.put(BillTypeConst.PATROL_BILLTYPE ,queryInfo);
        }else{
            pageQueryServiceMap.put(queryInfo.getBillType(),queryInfo);
        }
    }

    @Autowired
    private DiscussInternalOperation discussOperation;

    //留言数量
    public static final String COMMENT_COUNT = "commentCount";


    @Override
    public PMListQueryResult queryListByPrj(QueryListParam queryListParam) throws BusinessException {

        PMListQueryResult result = new PMListQueryResult();

        if(queryListParam == null)
            return result;
        if(StringUtils.isEmpty(queryListParam.getFisrtQueryDate())){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            result.setFirstQueryDate(sdf.format(new Date()));
        }else{
            result.setFirstQueryDate(queryListParam.getFisrtQueryDate());
        }

        IPageQuerySerivce pageQuerySerivce = pageQueryServiceMap.get(queryListParam.getBillType());
        if(pageQuerySerivce == null)
            return result;

        initParam(queryListParam);

        Integer totalNum = pageQuerySerivce.countByProject(queryListParam);

        if(totalNum == null || totalNum == 0){
            result.setTotalNum(0);
            return result;
        }

        SuperVO[] busiVOs = pageQuerySerivce.queryByProject(queryListParam);
        if(ArrayUtils.isEmpty(busiVOs))
            return result;

        Map<String,Map<String,Object>> additionalMap = getIdPropMap(busiVOs);

        result.setTotalNum(totalNum);
        result.setBusiVOs(wrapAdditionalProps(busiVOs,additionalMap));

        return result;
    }

    /**
     * 初始化查询参数
     *
     * @param queryListParam
     */
    private void initParam(QueryListParam queryListParam) {
        if(queryListParam.getPageSize() == null)
            queryListParam.setPageSize(50);

        if(queryListParam.getPageStart() == null)
            queryListParam.setPageStart(0);

        String endDate = "";
        String fisrtQueryDate = queryListParam.getFisrtQueryDate();
        if(StringUtils.isNotEmpty(fisrtQueryDate)){
            endDate = fisrtQueryDate;
        }else{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            endDate = sdf.format(new Date());
        }
        queryListParam.setEndDate(endDate);
        queryListParam.setStartDate(DateUtils.INIT_DATE_STRING);
    }


    private Map<String,Map<String,Object>> getIdPropMap(SuperVO[] superVOs){

        Map<String,Map<String,Object>> result = new HashMap<>();

        if (ArrayUtils.isEmpty(superVOs))
            return result;

        Map<String,Integer> commentMap = getCommentCount(getIds(superVOs));

        buildPropMap(result,COMMENT_COUNT,commentMap);

        return result;
    }

    private String[] getIds(SuperVO[] vos){

        if(ArrayUtils.isEmpty(vos))
            return new String[0];

        List<String> idList = new ArrayList<>();
        for (SuperVO vo : vos){
            idList.add(BeanHelper.getId(vo));
        }
        return idList.toArray(new String[0]);
    }

    private Map<String,Map<String,Object>> buildPropMap(Map<String,Map<String,Object>> result,String propName,Map<String,?> map){
        if (map != null) {
            for (Map.Entry<String, ?> entry : map.entrySet()) {
                String s=entry.getKey();
                Object i=entry.getValue();

                if(result.get(s) == null){
                    Map<String, Object> prop = new HashMap<>(1);
                    result.put(entry.getKey(), prop);
                }
                result.get(s).put(propName, entry.getValue());
            }
        }
        return result;

    }

    private Map<String,Integer> getCommentCount(String[] ids){
        Map<String, Integer> discussCounts = new HashMap<>(ids.length);
        if (ArrayUtils.isEmpty(ids))
            return discussCounts;
        // 获取评论数
        try{
            discussCounts = discussOperation.countDiscussion(ids);
        }catch(Exception e){
            log.error(e.getMessage(),e);
        }
        return discussCounts;
    }

    private <T extends Entity> AdditionalPropertiesVOWrapper[] wrapAdditionalProps(T[] vos,Map<String, Map<String, Object>> additionProperties) throws BusinessException {
        //判断其插入数组是否为空
        if (ArrayUtils.isEmpty(vos)) {
            return new AdditionalPropertiesVOWrapper[0];
        }
        AdditionalPropertiesVOWrapper[] wrappers = new AdditionalPropertiesVOWrapper[vos.length];
        //  创建一个单据ID的数组
        String[] ids = new String[vos.length];
        for (int i = 0; i < ids.length; i++) {
            ids[i] = (String) vos[i].pkFiledValue();
        }

        for (int i = 0; i < vos.length; i++) {
            wrappers[i] = new AdditionalPropertiesVOWrapper<>(vos[i]);
            Map<String, Object> properties = additionProperties.get(vos[i].pkFiledValue());
            if (properties == null || properties.isEmpty()) {
                continue;
            }
            for (Map.Entry<String, Object> entry : properties.entrySet()) {
                wrappers[i].addProperties(entry.getKey(), entry.getValue());
            }
        }
        return wrappers;
    }
}

